package com.web.kdl.service.send;

import com.serotonin.modbus4j.ModbusMaster;
import com.web.kdl.config.modbus.Modbus4jFactory;
import com.web.kdl.entity.matrix.Matrix;
import com.web.kdl.entity.site.Site;
import com.web.kdl.service.flywheelDataAnalysis.FlywheelDataAnalysisService;
import com.web.kdl.service.site.SiteService;
import com.web.kdl.util.Modbus4jUtils;
import com.web.kdl.util.ModbusUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class SendServiceImpl implements SendService {

    @Autowired
    private MqttService mqttService;
    @Autowired
    private Modbus4jFactory modbus4jFactory;
    @Autowired
    private Modbus4jUtils modbus4jUtils;
    @Autowired
    private FlywheelDataAnalysisService flywheelDataAnalysisService;

    @Autowired
    private SiteService siteService;

    @Value("${mqtt.transactionId}")
    private int transactionId;
    @Override
    @Async
    public void sendMatrix(Matrix matrix) {
        try {
            Integer wheelNumber = matrix.getWheelNumber();
            String topic = matrix.getTopic();

            if (wheelNumber > 4) {
                log.error("飞轮数量不能大于4");
            }

            log.info("{} 开始发送矩阵 {}", Thread.currentThread().getName(), matrix.getMatrixName());

            for (int i = 0; i < wheelNumber; i++) {
                // 第一段数据
                String hexDataFly1 = ModbusUtil.buildReadHolding(transactionId, i + 1, 200 * i + 40001, 100);
                log.info("发送数据，阵列id:{},飞轮序号:{},寄存器大小:{}",matrix.getId(),i+1,100 );
                mqttService.sendHexData(hexDataFly1, topic);
                Thread.sleep(1000);

                // 第二段数据
                String hexDataFly2 = ModbusUtil.buildReadHolding(transactionId, i + 1, 200 * i + 40101, 80);
                log.info("发送数据，阵列id:{},飞轮序号:{},寄存器大小:{}",matrix.getId(),i+1,80 );
                mqttService.sendHexData(hexDataFly2, topic);
                Thread.sleep(1000);
            }

            // 总控信息
            log.info("发送总线数据，阵列id:{},,寄存器大小:{}",matrix.getId(),98 );
            String hexData2 = ModbusUtil.buildReadHolding(transactionId, 0, 40801, 98);
            mqttService.sendHexData(hexData2, topic);
            log.info("{} 矩阵 {} 下发完成", Thread.currentThread().getName(), matrix.getMatrixName());

        } catch (Exception e) {
            log.error("异步任务异常：{}", e.getMessage(),e);
        }
    }

    @Override
    @Async
    public void getModBusMatrix(Matrix matrix) {
        Site site = siteService.getSiteById(matrix.getSiteId());
        if(matrix.getIp()==null|| matrix.getIp().isEmpty()){
            return;
        }
        ModbusMaster master = modbus4jFactory.getDeviceConnection(String.valueOf(matrix.getId()), matrix.getIp(), matrix.getPort());
        if (master != null) {
            log.info("开始获取矩阵 {}", matrix.getMatrixName());
            for (int i = 0; i < matrix.getWheelNumber() && i < 4; i++) {

                log.info("获取数据，阵列id:{},飞轮序号:{},寄存器大小:{}",matrix.getId(),i+1,100 );
                String hexDataFly1 = ModbusUtil.buildReadHolding(matrix.getId(), i + 1, 200 * i + 40001, 100);
                byte[] bytes100 = modbus4jUtils.executeAndGetCompleteRawBytes(master, hexDataFly1);
                int flyWheelSerial100 = bytes100[6] & 0xFF;
                flywheelDataAnalysisService.flywheel100(bytes100,"flywheel"+flyWheelSerial100, site.getSumSite(),matrix.getMatrixName(), "flywheel"+flyWheelSerial100,matrix.getId(),flyWheelSerial100);

                String hexDataFly2 = ModbusUtil.buildReadHolding(matrix.getId(), i + 1, 200 * i + 40101, 80);
                log.info("获取数据，阵列id:{},飞轮序号:{},寄存器大小:{}",matrix.getId(),i+1,80 );
                byte[] bytes80 = modbus4jUtils.executeAndGetCompleteRawBytes(master, hexDataFly2);
                int flyWheelSerial80 = bytes80[6] & 0xFF;
                flywheelDataAnalysisService.flywheel80(bytes80, "flywheel"+flyWheelSerial80, site.getSumSite(),matrix.getMatrixName(),"flywheel"+flyWheelSerial80,matrix.getId(),flyWheelSerial80);
            }
            String hexData2 = ModbusUtil.buildReadHolding(matrix.getId(), 1, 40801, 98);
            byte[] bytes98 = modbus4jUtils.executeAndGetCompleteRawBytes(master, hexData2);
            int flyWheelSerial98 = bytes98[6] & 0xFF;
            flywheelDataAnalysisService.flywheel98(bytes98, "总控制信息", site.getSumSite(),matrix.getMatrixName() , "flywheel"+flyWheelSerial98);
        }
    }
}



